import Arcs from "./Arcs"

// 擦除类
export default class {
  size = 20
  scene: any
  private enable: boolean = false
  private mousedownFn: any
  private mousemoveFn: any
  private mouseupFn: any
  private points: [number, number][] = []
  constructor(scene: any) {
    this.scene = scene
  }
  open() {
    const { domElement, ctx, osCtx } = this.scene
    this.mousedownFn = this.mousedown.bind(this, ctx, osCtx)
    this.mousemoveFn = this.mousemove.bind(this, ctx, osCtx)
    this.mouseupFn = this.mouseup.bind(this, ctx, osCtx)
    domElement.addEventListener('mousedown', this.mousedownFn)
    domElement.addEventListener('mousemove', this.mousemoveFn)
    domElement.addEventListener('mouseup', this.mouseupFn)
  }
  close() {
    const { domElement } = this.scene
    domElement.removeEventListener('mousedown', this.mousedownFn)
    domElement.removeEventListener('mousemove', this.mousemoveFn)
    domElement.removeEventListener('mouseup', this.mouseupFn)
  }
  draw(x: number, y: number, ctx: CanvasRenderingContext2D, osCtx: OffscreenCanvasRenderingContext2D) {
    ctx.save()
    ctx.beginPath()
    ctx.arc(x, y, this.size, 0, Math.PI * 2)
    ctx.clip()
    ctx.clearRect(0, 0, this.scene.width, this.scene.height)
    ctx.closePath()
    ctx.restore()

    osCtx.save()
    osCtx.beginPath()
    osCtx.arc(x, y, this.size, 0, Math.PI * 2)
    osCtx.clip()
    osCtx.clearRect(0, 0, this.scene.width, this.scene.height)
    osCtx.closePath()
    osCtx.restore()

    this.points.push([x, y])
  }
  mousedown = (ctx: any, event: MouseEvent) => {    
    this.enable = true
  }
  mousemove = (ctx: any, osCtx: any, event: MouseEvent) => {
    if (!this.enable) return    
    this.draw(event.offsetX, event.offsetY, ctx, osCtx)
  }
  mouseup = (ctx: any, event: MouseEvent) => {
    const { domElement } = this.scene
    const backgroundColor = window.getComputedStyle(domElement,null).getPropertyValue('background-color')

    this.scene.shapes.push(new Arcs(this.points,this.size,backgroundColor))
    this.scene.setHistory()
    this.enable = false
  }
}